package appnode;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.servlet.http.*;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import appnode.Tablemsgs;
import appnode.Messages;
import appnode.PMF;

public class Addmsg extends HttpServlet {

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
	
		PersistenceManager pm = PMF.get().getPersistenceManager();
		UserService userService = UserServiceFactory.getUserService();
		String fromnode = req.getParameter("fromnode");
		//HttpSession session = req.getSession(true);
		//String fromnode = (String) session.getAttribute("currentnode");
		String tonode = req.getParameter("tonode"); 
		String subject = req.getParameter("subject");
		String status = req.getParameter("status");
		String content = req.getParameter("content");
		String typeofmsg = req.getParameter("typeofmsg");
		String msgform = req.getParameter("msgform");
		Messages newcontent = new Messages(fromnode,tonode,content,new Date());
		
		if (typeofmsg.equals("newmsg")) {
			Tablemsgs newmsg = new Tablemsgs(fromnode,tonode,subject,new Date(),new Date());
			pm.makePersistent(newmsg);
			newmsg.getMessages().add(newcontent);
			if (msgform.equals("messgform")) {
			resp.sendRedirect("/tablmsg.jsp?nodename=" + fromnode);
			}
			else if (msgform.equals("msgform")) {
				resp.setContentType("text/html");
				resp.getWriter().println("<html>");
				resp.getWriter().println("You send the message succesfully");
				resp.getWriter().println("<br>");
				resp.getWriter().println("<input type='button' value='Ok' onClick='self.close()'/>");
				resp.getWriter().println("</html>");
			}
		}
		else {			
			//update
			String skey = req.getParameter("skey"); 
			Key key = KeyFactory.stringToKey(skey);
			Tablemsgs msg = pm.getObjectById(Tablemsgs.class,key);
			msg.getMessages().add(newcontent);
			msg.setUpdate(new Date());
			resp.sendRedirect("/showmsgs.jsp?fromnode="+fromnode+"&id=" + skey);
		}	 
	pm.close();
	}
}